package com.zizo.util;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Inflater;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.nlpcn.commons.lang.util.WordAlert;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

public class Util {

	// 给定字符串和正则表达式，判断是否匹配
	public static boolean isMatched(String str, String regex) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		// System.out.println(matcher);
		return matcher.matches();
	}

	// 给定字符串和正则表达式，获得匹配的字
	public static Matcher getMatched(String str, String regex) {
		Matcher match = null;
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		if (matcher.find()) {
			match = matcher;
		}
		return match;

	}

	/**
	 * @Title: getDate
	 * @Description: TODO 获得格式化日期，用在向数据库中插入日期的字符串 2000-10-01
	 * @param date
	 * @return
	 * @return: Date
	 * @author: Alexis
	 */
	public static Date getDate(String date) {
		Date time = null;
		String s1 = date.replace("年", "-");
		String s2 = s1.replace("月", "-");
		String s3 = s2.replace("日", "");
		try {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			time = format.parse(s3);
		} catch (ParseException e) {
			DateFormat format = new SimpleDateFormat("yyyy-MM");
			try {
				time = format.parse(s3);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
		}

		java.sql.Date sqlDate = new java.sql.Date(time.getTime());
		return sqlDate;
	}

	/**
	 * @Title: getTime
	 * @Description: TODO 获得格式化日期+时间，参数为时间的字符串
	 * @param date
	 * @return
	 * @return: Date
	 * @author: Alexis
	 */
	public static Date getTimeHM(String date) {
		Date time = null;
		String s1 = date.replace("年", "-");
		String s2 = s1.replace("月", "-");
		String s3 = s2.replace("日", "");
		try {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			time = format.parse(s3);
		} catch (ParseException e) {
			DateFormat format = new SimpleDateFormat("yyyy-MM");
			try {
				time = format.parse(s3);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
		}

		java.sql.Timestamp sqlDate = new java.sql.Timestamp(time.getTime());
		return sqlDate;
	}

	/**
	 * @Title: getTime
	 * @Description: TODO 获得格式化日期+时间，参数为时间的字符串
	 * @param date
	 * @return
	 * @return: Date
	 * @author: Alexis
	 */
	public static Date getTimeHMS(String date) {
		Date time = null;
		String s1 = date.replace("年", "-");
		String s2 = s1.replace("月", "-");
		String s3 = s2.replace("日", "");
		try {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			time = format.parse(s3);
		} catch (ParseException e) {
			DateFormat format = new SimpleDateFormat("yyyy-MM");
			try {
				time = format.parse(s3);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
		}

		java.sql.Timestamp sqlDate = new java.sql.Timestamp(time.getTime());
		return sqlDate;
	}

	public static String getStandDate(String s) {
		String s1 = s.replace("年", "-");
		String s2 = s1.replace("月", "-");
		String s3 = s2.replace("日", "");
		return s3;

	}

	// 将抓取的表情符号过滤掉
	public static String deleteChar(String data) {
		byte[] b = data.getBytes();
		byte[] by = new byte[b.length];
		for (int i = 0; i < b.length;) {
			if (b[i] == -16) {
				i += 4;
			} else {
				by[i] = b[i];
				i++;
			}
		}
		return new String(by);
	}

	/**
	 * 字符串编码转换的实现方法
	 * 
	 * @param str
	 *            待转换编码的字符串
	 * @param newCharset
	 *            目标编码
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String changeCharset(String str, String newCharset) {
		if (str != null) {
			// 用默认字符编码解码字符串。
			byte[] bs = str.getBytes();
			// 用新的字符编码生成字符串
			try {
				return new String(bs, newCharset);
			} catch (UnsupportedEncodingException e) {
			}
		}
		return null;
	}

	/**
	 * @Title: downloadWebsite
	 * @Description: 下载镜像文件,createNewFile()只能在已有的目录下创建文件，不能多目录创建 eg：D:/1/2/3
	 *               只有目录1的情况下回发生异常，只有目录1/2时正常
	 * @param pathname
	 * @param doc
	 * @return: void
	 * @author: Alexis
	 */
	public static void downloadWebsite(String pathname, String filename, String data) {
		File f = new File(pathname);
		f.mkdirs();
		String filepath = pathname + "/" + filename;
		Path pathfile = Paths.get(filepath);
		boolean pathfile_exists = Files.exists(pathfile, new LinkOption[] { LinkOption.NOFOLLOW_LINKS });
		if (pathfile_exists) {
			try (FileOutputStream testfile = new FileOutputStream(filepath)) {
				testfile.write(new String("").getBytes());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				Files.createFile(pathfile);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {

			BufferedWriter bw = null;
			FileWriter fw = null;
			File file = new File(pathname + "/" + filename);
			fw = new FileWriter(file);
			bw = new BufferedWriter(fw);
			bw.write(data);
			bw.flush();
			fw.close();
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * @Title: readFile
	 * @Description: 获取文件内容，返回Document
	 * @param pathname
	 * @return
	 * @return: Document
	 * @author: Alexis
	 */
	// public static Document readFile(String pathname) {
	// File file = new File(pathname);
	// StringBuffer sb = new StringBuffer();
	// try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
	// String tempString = null;
	// // 一次读入一行，直到读入null为文件结束
	// while ((tempString = reader.readLine()) != null) {
	// sb.append(tempString);
	// }
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// return Jsoup.parse(sb.toString());
	// }
	public static Document readFile(String pathname) {
		File file = new File(pathname);
		Document doc = null;
		try {
			doc = Jsoup.parse(file, "gbk");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}

	/**
	 * @Title: removeFullWidth
	 * @Description: TODO 全角转为半角,大写
	 * @return String
	 * @author HeYan
	 */
	public static String removeFullWidth(String data) {
		char[] result = WordAlert.alertStr(data);
		data = new String(result);
		return data.toUpperCase().trim().replaceAll("\n\n", "\n");
	}

	/**
	 * @Title: getdDirectory
	 * @Description: 获取给定目录下的所有直接目录
	 * @param pathname
	 * @return
	 * @return: File[]
	 * @author: Alexis
	 */
	public static List<File> getDirectDirectory(String pathname) {
		File file = new File(pathname);
		List<File> list = new ArrayList<>();
		File[] files = file.listFiles();
		for (File f : files) {
			if (f.isDirectory()) {
				list.add(f);
			}
		}
		return list;
	}

	/**
	 * @Title: getFileList
	 * @Description: 获取给定目录下的所有html文件
	 * @param strPath
	 * @return
	 * @return: List<File>
	 * @author: Alexis
	 */
	public static List<File> getFileList(String strPath) {
		List<File> filelist = new ArrayList<>();
		File dir = new File(strPath);
		File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getName();
				if (files[i].isDirectory()) { // 判断是文件还是文件夹
					filelist.addAll(getFileList(files[i].getAbsolutePath())); // 获取文件绝对路径
				} else if (fileName.endsWith("html")) { // 判断文件名是否以.html结尾
					filelist.add(files[i]);
				} else {
					continue;
				}
			}
		}
		return filelist;
	}

	/**
	 * @Title: getCurrentDateTime
	 * @Description: 得到当前的系统的时间
	 * @return
	 * @return: String
	 * @author: Alexis
	 */
	public static String getCurrentDateTime() {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		return df.format(new Date());
	}

	public String secondToDate(long second) {
		Date dat = new Date(second);
		GregorianCalendar gc = new GregorianCalendar();
		gc.setTime(dat);
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String sb = format.format(gc.getTime());
		return sb;
	}

	/**
	 * @Title: addFileToZip
	 * @Description: TODO 向压缩文件中添加原始文件，添加后删除原始文件
	 * @param srcPath
	 *            向压缩文件添加的原始文件
	 * @param tarPath
	 *            压缩文件路径
	 * @return void
	 * @author Alexis
	 */
	public static void addFileToZip(String srcPath, String tarPath) {
		try {
			ZipFile zipFile = new ZipFile(tarPath);
			ZipParameters parameters = new ZipParameters();
			parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set
			parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
			File file = new File(srcPath);
			zipFile.addFile(file, parameters);
			file.delete();
		} catch (ZipException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解压缩
	 * 
	 * @param data
	 *            待压缩的数据
	 * @return byte[] 解压缩后的数据
	 */
	public static byte[] decompress(byte[] data) {
		byte[] output = new byte[0];

		Inflater decompresser = new Inflater();
		decompresser.reset();
		decompresser.setInput(data);

		ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
		try {
			byte[] buf = new byte[1024];
			while (!decompresser.finished()) {
				int i = decompresser.inflate(buf);
				o.write(buf, 0, i);
			}
			output = o.toByteArray();
		} catch (Exception e) {
			output = data;
			e.printStackTrace();
		} finally {
			try {
				o.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		decompresser.end();
		return output;
	}

	/**
	 * @Title: compare_date
	 * @Description: TODO 比较2个日期的大小
	 * @param DATE1
	 * @param DATE2
	 * @return
	 * @return int
	 * @author Alexis
	 */
	public static int compare_date(String DATE1, String DATE2) {

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date dt1 = df.parse(DATE1);
			Date dt2 = df.parse(DATE2);
			if (dt1.getTime() > dt2.getTime()) {
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {
				return -1;
			} else {
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}

	public static void main(String[] args) throws Exception {
		System.out.println(Util.compare_date("2015-10-10", "2014-10-1 12:33"));
	}
}
